package com.pmdb.util;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.pmdb.core.data.Person;

public class PersonUtil {

   private static final Logger LOG = Logger.getLogger(PersonUtil.class);
   
   private static final int NUM_ITEMS = 14;

   private static final String[] persons = new String[] {
      "Kim Ki-duk",
      "Chan-wook Park",
      "Akira Kurosawa",
      "Takeshi Kitano",
      "Kar Wai Wong",
      "Ho-Cheung Pang",
      "Steven Spielberg",
      "Martin Brest",
      "Oliver Stone",
      "Jean-Jacques Annaud",
      "Luc Besson",
      "Shekhar Kapur",
      "Gus Van Sant",
      "Robert Zemeckis"};

   private static int personIdx = -1;
   private static List<Person> items = new ArrayList<Person>();
   private EntityManager em = null;

   public PersonUtil(EntityManager em) {
      this.em = em;
   }

   public void generatePerson() {
     for (int i = 0; i < NUM_ITEMS; ++i) {
       items.add(createPerson());
     }
   }

   public Person getPerson(int index) {
     if (index >= items.size()) {
       return null;
     }
     return items.get(index);
   }

   public int getGenreCount() {
     return items.size();
   }

   private Person createPerson() {
     personIdx++;
     return new Person(persons[personIdx]);
   }

   private Person createPerson(String name) {
      Person newPerson = new Person(name);
     em.persist(newPerson);
     return newPerson;
   }

   public Person findPersonByName(String name) {
      Query personByName = em.createQuery("from Person p where p.fullName like :name");
      personByName.setParameter("name", name);

      if(personByName.getResultList().size() == 0) {
         LOG.debug("Not Found: " + name);
         return null;
      }
      else {
         LOG.debug("Found: " + name);
         return (Person)personByName.getSingleResult();
      }
   }

   public Person findOrCreate(String name) {
      Person person = this.findPersonByName(name);
      if(person == null) {
         person = this.createPerson(name);
         LOG.debug("Person: " + name + " not found! (created)");
      }
      return person;
   }
}
